<?php

class PtbhadarateController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
//	public $layout='//layouts/column2';
    public $layout = '//layouts/eastsouthwest';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'view', 'jsonmessage'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'update', 'gridupdate', 'generate'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('popupview', 'admin', 'delete'),
                'users' => array('admin'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Ptbhadarate;

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if (isset($_POST['Ptbhadarate'])) {
            $model->attributes = $_POST['Ptbhadarate'];
            if ($model->save())
                $this->redirect(array('create', 'id' => $model->idptbhadarate));
//				$this->redirect(array('view','id'=>$model->idptbhadarate));
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if (isset($_POST['Ptbhadarate'])) {
            $model->attributes = $_POST['Ptbhadarate'];
            if ($model->save())
                $this->redirect(array('admin'));
//				$this->redirect(array('view','id'=>$model->idptbhadarate));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('Ptbhadarate');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Ptbhadarate('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Ptbhadarate']))
            $model->attributes = $_GET['Ptbhadarate'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Manages popupview.
     */
    public function actionPopupview() {
        $model = new Ptbhadarate('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Ptbhadarate']))
            $model->attributes = $_GET['Ptbhadarate'];

        if (isset($_REQUEST['isAjaxRequest']) && $_REQUEST['isAjaxRequest'] == '1') {
            Yii::app()->clientscript->scriptMap['jquery.js'] = false;
            echo CJSON::encode(array(
                'status' => 'failure',
                'div' => $this->renderPartial('popupview', array('model' => $model, 'id' => $_REQUEST['id']), true, true)));
            exit;
        }

        $this->render('popupview', array(
            'model' => $model, 'id' => ''
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = Ptbhadarate::model()->findByPk((int) $id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'ptbhadarate-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionJsonmessage() {
        $jsonmessage = array();
        $jsonmessage['status code'] = 200;
        $jsonmessage['message'] = ' - ';
        if (isset($_REQUEST['cid'])) {
            $model = Ptbhadarate::model()->findByPk($_REQUEST['cid']);
            if ($model) {
                $jsonmessage['message'] = $model->aresidential;
            }
        }

        header('Content-type: application/json');
        echo CJSON::encode($jsonmessage);
        Yii::app()->end();
    }

    public function actionGridupdate() {

        $ptbhadarates = array();
        $ptbhadarates = $_POST['Ptbhadarate'];
        $valid = true;
        $errors = array();
        foreach ($ptbhadarates as $key => $value) {

            $model = $this->loadModel($key);
            $model->attributes = $value;
//            if(!$model->validate(NULL, false)){
            if (!$model->save()) {
                $valid = false;

                $model_errors = $model->getErrors();
                foreach ($model_errors as $mekey => $mevalue) {
                    foreach ($mevalue as $key => $value) {
                        $errors[$model->idptbhadarate . '_' . $mekey] = $value . " (" . $model->idccward0->idcczone0->zonename . " - " . $model->idccward0->wardname . ")";
                    }
                }
            }
        }


        $model_new = new Ptbhadarate('search');
        $model_new->unsetAttributes();  // clear any default values
        if (isset($_GET['Ptbhadarate']))
            $model->attributes = $_POST['Ptbhadarate'];

        $model_new->addErrors($errors);

        $this->render('admin', array(
            'model' => $model_new,
        ));
    }

    public function actionGridupdate_original() {
        //update aresidential column
        $rates = $_REQUEST['aresidential'];
        foreach ($rates as $key => $value) {
            $sql = "Update {{ptbhadarate}} set aresidential=$value WHERE idptbhadarate=$key";
            $connection = Yii::app()->db;
            $connection->createCommand($sql)->execute();
        }
        //update acommercial column
        $rates = $_REQUEST['acommercial'];
        foreach ($rates as $key => $value) {
            $sql = "Update {{ptbhadarate}} set acommercial=$value WHERE idptbhadarate=$key";
            $connection = Yii::app()->db;
            $connection->createCommand($sql)->execute();
        }
        //update bresidential column
        $rates = $_REQUEST['bresidential'];
        foreach ($rates as $key => $value) {
            $sql = "Update {{ptbhadarate}} set bresidential=$value WHERE idptbhadarate=$key";
            $connection = Yii::app()->db;
            $connection->createCommand($sql)->execute();
        }
        //update bcommercial column
        $rates = $_REQUEST['bcommercial'];
        foreach ($rates as $key => $value) {
            $sql = "Update {{ptbhadarate}} set bcommercial=$value WHERE idptbhadarate=$key";
            $connection = Yii::app()->db;
            $connection->createCommand($sql)->execute();
        }
        //update cresidential column
        $rates = $_REQUEST['cresidential'];
        foreach ($rates as $key => $value) {
            $sql = "Update {{ptbhadarate}} set cresidential=$value WHERE idptbhadarate=$key";
            $connection = Yii::app()->db;
            $connection->createCommand($sql)->execute();
        }
        //update ccommercial column
        $rates = $_REQUEST['ccommercial'];
        foreach ($rates as $key => $value) {
            $sql = "Update {{ptbhadarate}} set ccommercial=$value WHERE idptbhadarate=$key";
            $connection = Yii::app()->db;
            $connection->createCommand($sql)->execute();
        }
        //update dresidential column
        $rates = $_REQUEST['dresidential'];
        foreach ($rates as $key => $value) {
            $sql = "Update {{ptbhadarate}} set dresidential=$value WHERE idptbhadarate=$key";
            $connection = Yii::app()->db;
            $connection->createCommand($sql)->execute();
        }
        //update dcommercial column
        $rates = $_REQUEST['dcommercial'];
        foreach ($rates as $key => $value) {
            $sql = "Update {{ptbhadarate}} set dcommercial=$value WHERE idptbhadarate=$key";
            $connection = Yii::app()->db;
            $connection->createCommand($sql)->execute();
        }

        $this->redirect(array('ptbhadarate/admin'));
    }

    public function actionGenerate() {
        if (isset(Yii::app()->session['ccfyear'])) {
            $idccfyear = Yii::app()->session['ccfyear']->idccfyear;
            $ccfyear_previous = Ccfyear::model()->findbypk((int) $idccfyear - 1);
        }

        $criteria = new CDbCriteria;
        $criteria->compare('idccfyear', $idccfyear, true);
        $ptbhadarates = Ptbhadarate::model()->findAll($criteria);
        if (count($ptbhadarates) == 0) {

            if (isset($ccfyear_previous) && $ccfyear_previous) {
                $criteria = new CDbCriteria;
                $criteria->compare('idccfyear', $ccfyear_previous->idccfyear, true);
                $ptbhadarates = Ptbhadarate::model()->findAll($criteria);
            }

            $ccwards = Ccward::model()->findAll();
            foreach ($ccwards as $ccward) {
                $ptbhadarate = new Ptbhadarate();
                $ptbhadarate->idccfyear = $idccfyear;
                $ptbhadarate->idccward = $ccward->idccward;
                if (isset($ptbhadarates) && count($ptbhadarates) > 0) {
                    foreach ($ptbhadarates as $ptbhadaratevalue) {
                        if ($ccward->idccward == $ptbhadaratevalue->idccward) {
                            $ptbhadarate->aresidential = $ptbhadaratevalue->aresidential;
                            $ptbhadarate->acommercial = $ptbhadaratevalue->acommercial;
                            $ptbhadarate->bresidential = $ptbhadaratevalue->bresidential;
                            $ptbhadarate->bcommercial = $ptbhadaratevalue->bcommercial;
                            $ptbhadarate->cresidential = $ptbhadaratevalue->cresidential;
                            $ptbhadarate->ccommercial = $ptbhadaratevalue->ccommercial;
                            $ptbhadarate->dresidential = $ptbhadaratevalue->dresidential;
                            $ptbhadarate->dcommercial = $ptbhadaratevalue->dcommercial;
                        }
                    }
                }
                echo $ptbhadarate->idccward . ' ' . $ptbhadarate->aresidential . '</br>';
                $ptbhadarate->save();
            }
            Yii::app()->user->setFlash('success', Yii::t('application', 'Ptbhadarate for current finanical year has been generated successfully.'));
        } else {
            Yii::app()->user->setFlash('notice', Yii::t('application', 'Ptbhadarate for current finanical year already exist.'));
        }
        $this->redirect(array('ptbhadarate/admin'));
    }

}
